package repo

import (
	"gitee.com/gomaster/book-library/entity"
	"gitee.com/gomaster/book-library/repo/memory"
)

var repoHandler *RepoHandler

// InitRepoHandler 初始化存储操作句柄
func InitRepoHandler(storeType string) {
	repoHandler = NewRepoBookHandler(storeType)
}

// GetRepoHandler 获取存储操作句柄
func GetRepoHandler() *RepoHandler {
	if repoHandler == nil {
		InitRepoHandler("memory")
	}
	return repoHandler
}

// RepoHandler 接口操作结构体
type RepoHandler struct {
	RepoBook
	RepoUser
	RepoBorrow
}

// RepoBook 图书相关接口
type RepoBook interface {
	BookAdd(bk *entity.BookInfo) error
	BookGet(ibsn string) *entity.BookInfo
	BookDel(ibsn string) error
	BookUpdate(ibsn string, bk *entity.BookInfo) error
	BookList() []*entity.BookInfo
}

// RepoUser 用户相关接口
type RepoUser interface {
	UserAdd(us *entity.UserInfo) error
	UserGet(name string) *entity.UserInfo
	UserDel(name string) error
	UserUpdate(name string, bk *entity.UserInfo) error
	UserList() []*entity.UserInfo
}

// RepoBorrow 图书借阅接口
type RepoBorrow interface {
	BorrowAdd(ibsn, username string) error
	BorrowGet(ibsn string) *entity.BorrowRecord
	BorrowBack(ibsn, userName string) error
	BorrowListByName(name string) []*entity.BorrowRecord
	BorrowListByBookName(ibsn string) []*entity.BorrowRecord
}

// NewRepoBookHandler 根据类型，实例化接口
func NewRepoBookHandler(storeType string) *RepoHandler {
	if storeType == "memory" {
		memBook := &memory.MemoryBook{}
		memUser := &memory.MemUser{}
		memBorrow := &memory.MemBorrow{}
		return &RepoHandler{
			memBook,
			memUser,
			memBorrow,
		}
	}
	return nil
}
